package com.meng.menggaga.ui;

import uk.co.senab.actionbarpulltorefresh.extras.actionbarcompat.AbcDefaultHeaderTransformer;
import uk.co.senab.actionbarpulltorefresh.extras.actionbarcompat.PullToRefreshLayout;
import uk.co.senab.actionbarpulltorefresh.library.ActionBarPullToRefresh;
import uk.co.senab.actionbarpulltorefresh.library.Options;
import uk.co.senab.actionbarpulltorefresh.library.listeners.OnRefreshListener;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.meng.menggaga.R;
import com.meng.menggaga.adapter.CommunityBannerAdapter;
import com.meng.menggaga.adapter.CommunityListAdapter;
import com.meng.menggaga.application.MainApplication;
import com.meng.menggaga.entity.CommunityInfos;
import com.meng.menggaga.entity.CommunityInfos.CommunityInfo;
import com.meng.menggaga.util.CommonParameter;
import com.meng.menggaga.util.Contants;
import com.nhaarman.listviewanimations.swinginadapters.AnimationAdapter;
import com.nhaarman.listviewanimations.swinginadapters.prepared.SwingBottomInAnimationAdapter;

/**
 * 社区列表
 * 
 * 版本：1.0.1，只做萌图社区
 * 
 * 首页列表，根据不同的分类来显示
 * 
 * @author simba
 * 
 */
public class CommunityListFragment extends BaseFragment implements
		OnRefreshListener {
	/**
	 * The fragment argument representing the section number for this fragment.
	 */
	private static final String ARG_SECTION_NUMBER = "section_number";

	private ListView vListView;
	private PullToRefreshLayout mPullToRefreshLayout;

	/**
	 * Returns a new instance of this fragment for the given section number.
	 */
	public static CommunityListFragment newInstance(int sectionNumber) {
		CommunityListFragment fragment = new CommunityListFragment();
		Bundle args = new Bundle();
		args.putInt(ARG_SECTION_NUMBER, sectionNumber);
		fragment.setArguments(args);
		return fragment;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View rootView = inflater.inflate(R.layout.fragment_community_list,
				container, false);

		vListView = (ListView) rootView.findViewById(R.id.listview);

		return rootView;
	}

	@Override
	public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);
		// We can now setup the PullToRefreshLayout

		mPullToRefreshLayout = new PullToRefreshLayout(view.getContext());
		AbcDefaultHeaderTransformer transformer = new AbcDefaultHeaderTransformer();
		ActionBarPullToRefresh
				.from(getActivity())
				// We need to insert the PullToRefreshLayout into the Fragment's
				// ViewGroup
				.insertLayoutInto((ViewGroup) view)
				.options(
						Options.create().headerTransformer(transformer).build())
				// Here we mark just the ListView and it's Empty View as
				// pullable
				.theseChildrenArePullable(R.id.listview).listener(this)
				.setup(mPullToRefreshLayout);

		// transformer.getHeaderView().setBackgroundColor(
		// getResources().getColor(CommonParameter.sStyleBgColor));
		transformer.setProgressBarColor(getResources().getColor(
				CommonParameter.sStyleBgColor));
		transformer.setProgressBarBgColor(getResources().getColor(
				CommonParameter.sStyleBgColor));
		transformer.setHeaderTextViewBgColor(getResources().getColor(
				CommonParameter.sStyleBgColor));
		vListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				Intent intent = new Intent(getActivity(),
						CommunityDetailActivity.class);
				intent.putExtra(Contants.KEY_COMMUNITY_INFO,
						(CommunityInfo) arg0.getAdapter().getItem(arg2));
				startActivity(intent);
			}
		});
		vListView.setOnScrollListener(new OnScrollListener() {

			@Override
			public void onScrollStateChanged(AbsListView arg0, int arg1) {

			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				if (firstVisibleItem >= 1) {
					// ((ActionBarActivity)
					// getActivity()).getSupportActionBar().hide();
				} else {
					// ((ActionBarActivity)
					// getActivity()).getSupportActionBar().show();
				}
			}
		});
	}

	@Override
	public void onActivityCreated(@Nullable Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		onLoadDatas();
	}

	private void onLoadDatas() {
		MainApplication
				.get()
				.getMoccaApi()
				.getCommunityList(39, Contants.PAGE_START, Contants.PAGE_SIZE,
						new Listener<CommunityInfos>() {

							@Override
							public void onResponse(CommunityInfos response) {
								if (null != getActivity()) {
									if (null != response) {
										View headerView = View
												.inflate(
														getActivity(),
														R.layout.layout_community_banner,
														null);
										ViewPager vViewPager = (ViewPager) headerView
												.findViewById(R.id.viewpager);

										vViewPager
												.setAdapter(new CommunityBannerAdapter(
														getActivity(),
														response.array));
										try {
											vViewPager.setPageTransformer(true,
													Contants.TRANSFORM_CLASSES
															.get(1).clazz
															.newInstance());
										} catch (java.lang.InstantiationException e) {
											e.printStackTrace();
										} catch (IllegalAccessException e) {
											e.printStackTrace();
										}

										vListView.addHeaderView(headerView);
										loadCommunitys();
									}
								}
							}
						}, new ErrorListener() {

							@Override
							public void onErrorResponse(VolleyError error) {
							}
						});
	}

	private void loadCommunitys() {// getArguments().getInt(ARG_SECTION_NUMBER)
		MainApplication.get().getMoccaApi()
				.getCommunityList(39, 1, 10, new Listener<CommunityInfos>() {

					@Override
					public void onResponse(CommunityInfos response) {
						if (null != getActivity()) {
							if (null != response) {
								CommunityListAdapter adapter = new CommunityListAdapter(
										getActivity(), response.array, 10,
										R.layout.list_item_community_list,
										R.layout.list_item_loading,
										R.layout.list_item_retry);
								AnimationAdapter animAdapter = new SwingBottomInAnimationAdapter(
										adapter);
								animAdapter.setAnimationDelayMillis(1000);
								animAdapter.setAnimationDurationMillis(3000);
								animAdapter.setAbsListView(vListView);

								vListView.setAdapter(animAdapter);

								mPullToRefreshLayout.setRefreshComplete();
							}
						}
					}
				}, new ErrorListener() {

					@Override
					public void onErrorResponse(VolleyError error) {
						mPullToRefreshLayout.setRefreshComplete();
					}
				});
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		// ((MainActivity)
		// activity).onSectionAttached(NAVIGATION_TYPE.COMMUNITY);
	}

	@Override
	public void onRefreshStarted(View view) {
		// Notify PullToRefreshLayout that the refresh has finished
		loadCommunitys();
	}
}
